package net.dgg.zz.production.completed.controller;

import net.dgg.common.tools.exception.ExceptionUtils;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.iboss.base.util.datatable.domain.DataTableResponse;
import net.dgg.tmd.foundation.platform.annotation.AuthOpt;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.OrderHandleUtils;
import net.dgg.zz.common.utils.excel.ExcelUtils;
import net.dgg.zz.production.abnormal.controller.ZzBaseController;
import net.dgg.zz.production.completed.service.ZzCompletedOrderService;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.vo.CompletedOrderVo;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>@Title 已完成订单Controller</p>
 * <p>@Description 负责已完成订单列表展示</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author @author 孙上峰</p>
 * <p>@date 2018-8-20 10:36:35 创建日期</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Controller
@RequestMapping("/zzsc/completed")
public class ZzCompletedOrderController extends ZzBaseController {
    @Autowired
    private ZzCompletedOrderService zzCompletedOrderService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private DesUtil desUtil;

    /**
     * 跳转到已完结生产订单列表页
     *
     * @return
     */
    @RequestMapping("/index")
    public String toCompletedOrderPage(ModelMap modelMap, String classify) {
        classify = classify == null ? "全部" : classify;
        Map statusMap = new LinkedHashMap();
        statusMap.put("全部", "");
        statusMap.put("正常完结", ScProductConstant.SC_ORDER_OVER);
        statusMap.put("超期完结", ScProductConstant.SC_ORDER_OVER_OVERDUE);
        statusMap.put("强制完结", ScProductConstant.SC_ORDER_OVER_FORCE);
        modelMap.addAttribute("statusMap", statusMap);
        modelMap.addAttribute("classify", classify);

        return "zzsc/completedOrder/page_order_completed";
    }

    /**
     * 查询我的已完结生产订单列表
     *
     * @return
     */
    @RequestMapping("/query_mycompleted_order")
    @ResponseBody
    public DataTableResponse queryMyCompletedOrder(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = this.generatePatameter(params, request);
        Map fileMap = new HashMap();
        fileMap.put("completedTime", "completedTime");
        fileMap.put("signTime", "signTime");
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> list = zzCompletedOrderService.query(params);
        int total = zzCompletedOrderService.count(params);
        return new DataTableResponse(r.getDraw(), total, total, list, "");

    }

    /**
     * 生产订单结项
     *
     * @param id
     * @return
     */
    @NLog
    @AuthOpt(code = "ZZSC_JUNCTIONS")
    @RequestMapping("/junctions_order")
    @ResponseBody
    public Object updateJunctionsOrder(Long id) {
        try {
            this.zzCompletedOrderService.updateJunctionsOrder(id);
            return this.getSuccessResponse("success!");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }


    /**
     * 导出
     * @param params
     * @return
     */
    @RequestMapping("export_sczz_completed")
    public void exportSczzCompleted(@RequestParam Map params, HttpServletResponse response) {
        try {
            String fileName = "已完结订单_" + DateUtils.dateString(new Date(), "yyyyMMddHHmm") + ".xlsx";
            List<CompletedOrderVo> dataList = zzCompletedOrderService.findByParamsList(params);
            ExcelUtils.writeToFile(dataList, null, fileName, response,CompletedOrderVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回完结待审核页面
     *
     * @return
     */
    @RequestMapping(value = "/close_auditHtml.html")
    public String closeAuditHtml(Model modelMap, String classify) {
        classify = classify == null ? "全部" : classify;
        Map statusMap = new LinkedHashMap();
        statusMap.put("待审核", "");
        statusMap.put("正常完结", ScProductConstant.SC_ORDER_JUNCTIONS);
        modelMap.addAttribute("statusMap", statusMap);
        modelMap.addAttribute("classify", classify);
        return "zzsc/closeAuditOrder/close_audit_order";
    }

    /**
     * 返回完结待审核页面
     *
     * @return
     */
    @RequestMapping(value = "/getCloseAuditOrderHtml.html")
    public String getCloseAuditOrderHtml(Model model, @RequestParam(value = "ids[]",required = false) List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            throw new ProductOrderExcption("未获取到订单id，请刷新页面重试");
        }
        if(ids.size() == 1){
            model.addAttribute("isShow",false);
        }else {
            model.addAttribute("isShow",true);
            model.addAttribute("orderList",zzCompletedOrderService.getCheckCloseAuditOrder(ids));
        }
        return "zzsc/closeAuditOrder/audit_order_dialog";
    }

    /**
     * 完结审核
     *
     * @param ids              订单id集合
     * @param type             审核类型 0 驳回 1 通过
     * @param remark           备注
     * @return
     */
    @RequestMapping(value = "/batch_close_audit.do")
    @ResponseBody
    public DggRestResponse batchCloseAudit(@RequestParam(value = "ids[]",required = false) List<Long> ids, Integer type, String remark) {

        try {
            //判断是否传递子订单id
            if (ids == null || ids.size() == 0) {
                return getFailResponse("未获取到订单id，请刷新页面重试");
            }
            //判断是否传递子订单id
            if (ids.size() > 10) {
                return getFailResponse("最多只能选择10条数据!");
            }
            if(StringUtils.isEmptyObj(type)){
                return getFailResponse("未获取到审核类型，请刷新页面重试");
            }
            if(type == 0 && StringUtils.isEmpty(remark)){
                return getFailResponse("未获取到驳回原因，请刷新页面重试");
            }
            //更新节点
            zzCompletedOrderService.batchCloseAudit(ids, type, remark);
            return getSuccessResponse(null);
        } catch (Exception e) {
            ExceptionUtils.error(e, "/zzsc/completed/batch_close_audit.do", ids, type, remark);
            return getFailResponse("操作失败");
        }

    }
}
